﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using AIS.SDK.Api.Response;
using AIS.SDK.Handler;
using AIS.SDK.Model;
using AISservice.Common;
using AISservice.Entity;
using Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace AISservice.Controllers
{
    [Route("api/v1/[controller]/[action]")]
    [ApiController]
    public class P4210UpdateController : ControllerBase
    {
        /// <summary>
        /// 更新带份额NW单数量
        /// 如果NW单中的明细不存在拣货单中，则删除处理
        /// </summary>
        /// <param name="objpram"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<MQResponse> UpdateNW(dynamic objpram)
        {
            Log4Net.Debug(objpram);
            P4210param param = Common.JsonHelper.JsonToObject<P4210param>((objpram).ToString());
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            int stackId = 0;
            int stateId = 0;
            string rid = "";
            string token = "";
            bool needclose = false;
            try
            {
                if (string.IsNullOrWhiteSpace(param.username) || string.IsNullOrWhiteSpace(param.password))
                {
                    throw new Exception("请求的用户名或密码为空！");
                }
               
                token = SomeHandler.GetToken(param.username, param.password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }

                Console.WriteLine($"username:{param.username} Token:{token}");


                var data = new BLL.orderHandler().GetNWOrder(param.orderid);
                if (data[0].Rows.Count <= 0)
                {
                    throw new Exception($"找不到NW单{param.ordernumber}对应的拣货单");
                }

                string NWOrderno = data[0].Rows[0]["JdeOrderno"].ToString().Replace("NW","");


                Console.WriteLine($"{DateTime.Now.ToString()} 查找NW单据 {NWOrderno}");

                #region 处理代码
                FormRequest formRequest = new FormRequest()
                {
                    //returnControlIDs = "1[45,46]",
                    formName = "P58E4210_W58E4210E",
                    version = "MBR001WD",
                    formServiceAction = "R",
                    bypassFormServiceEREvent = true
                   ,
                    formActions = new FormActionsCollection
                                 (
                                     new FSREvent[]
                                     {
                                      new FSREvent() { controlID="1[45]", command="SetQBEValue" ,value=NWOrderno },
                                      new FSREvent() { controlID="28", command="DoAction"  }
                                     }
                                 )
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    action = "open",
                    outputType = "VERSION2",
                    formName = "P58E4210_W58E4210E",
                    stackId = stackId,
                    stateId = stateId,
                    formRequest = formRequest

                };

                AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                //Console.WriteLine(response.JsonString);
                stackId = response.stackId;
                stateId = response.stateId;
                rid = response.rid;
                
                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P58E4210_W58E4210E"))
                {
                    JObject obj = response.ToJObject();
                    int rowcount = Convert.ToInt16(obj["fs_P58E4210_W58E4210E"]["data"]["gridData"]["summary"]["records"]);
                    Console.WriteLine($"查询到{rowcount - 1}条记录");


                    if (rowcount > 1)
                    {
                        Console.WriteLine("选择第一条记录，并打开编辑界面");
                        ActionRequest actionRequest = new ActionRequest()
                        {
                            //returnControlIDs = "1[53,89,35,132,133,34,664]",
                            formOID = "W58E4210E",
                            formActions = new FormActionsCollection
                                  (
                                      new FSREvent[]
                                      {
                                      new FSREvent() { controlID="1.0", command="SelectRow"   },
                                      new FSREvent() { controlID="4", command="DoAction"  }
                                      }
                                  )
                             ,
                            stopOnWarning = "false"
                        };

                        asrequest = new ApplicationStackRequest()
                        {
                            outputType = "VERSION2",
                            allowCache = true,
                            action = "execute",
                            actionRequest = actionRequest,
                            stackId = stackId,
                            stateId = stateId,
                            rid = response.rid
                        };
                        response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                        stackId = response.stackId;
                        stateId = response.stateId;
                        rid = response.rid;
                        if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P58E4210_W58E4210A"))
                        {
                            ///获取结果的总行数
                            obj = response.ToJObject();
                            rowcount = Convert.ToInt32(obj["fs_P58E4210_W58E4210A"]["data"]["gridData"]["summary"]["records"]);
                            List<gridrowupdateevents> gridrows = new List<gridrowupdateevents>();
                            List<gridcolumnevent> gridcols = new List<gridcolumnevent>();
                            List<int> delerows = new List<int>();


                            
                           
                            for (int i = 0; i < rowcount; i++)
                            {
                                Console.WriteLine($"正在处理第{i}行  原货位{obj["fs_P58E4210_W58E4210A"]["data"]["gridData"]["rowset"][i]["z_LOCN_132"]["value"].ToString()}");
                                stackId = response.stackId;
                                stateId = response.stateId;
                                int rowindex = Convert.ToInt32(obj["fs_P58E4210_W58E4210A"]["data"]["gridData"]["rowset"][i]["rowIndex"]);
                                //正常NW单带份额，需要ME码+批号+货位+份额 来区分

                                JObject details=(JObject)obj["fs_P58E4210_W58E4210A"]["data"]["gridData"]["rowset"][i];//["z_LOCN_132"]["value"].ToString()

                                string primaykey = $"itemnumber='{details["z_UITM_89"]["value"]}' " +
                                                    $"and lotn='{details["z_LOTN_133"]["value"]}' " +
                                                    $"and location='{details["z_LOCN_132"]["value"].ToString().Replace("-", " ").Trim()}' " +
                                                    $"and fromInvregion='{details["z_VR02_1065"]["value"]}' " +
                                                    $"and  ToInvregion='{details["z_VR01_608"]["value"]}' ";
                                Console.WriteLine(primaykey);
                                DataRow[] dr=data[0].Select(primaykey);
                                decimal NewQty = 0;
                                if (dr.Length > 0)
                                {
                                    NewQty = Convert.ToDecimal(dr[0]["quantity"].ToString());
                                    gridcols = new List<gridcolumnevent>();
                                    gridcols.Add(new gridcolumnevent()
                                    {
                                        columnID = "53",
                                        command = "SetGridCellValue",
                                        value = NewQty.ToString()
                                    }
                                    );
                                    gridrows.Add(new gridrowupdateevents()
                                    {
                                        gridColumnEvents = gridcols,
                                        rowNumber = rowindex
                                    });
                                }
                                else
                                {
                                    delerows.Add(rowindex);
                                }

                            }
                            List<FSREvent> formaction = new List<FSREvent>();
                            
                            delerows.ForEach(o=> {
                                formaction.Add(new FSREvent()
                                {
                                    controlID = $"1.{o}",
                                    command = "SelectRow"
                                });
                            });
                            //如果存在删除行，则删除
                            if (formaction.Count>0)
                                formaction.Add(new FSREvent() { controlID = "412", command = "DoAction" });
                            formaction.Add(new FSREvent()
                            {
                                controlID = "1.0",
                                command = "SelectRow",
                                gridAction = new GridAction() { gridID = "1", gridRowUpdateEvents = gridrows }
                            });
                            formaction.Add(new FSREvent() { controlID = "4", command = "DoAction" });



                            actionRequest = new ActionRequest()
                            {
                                //returnControlIDs = "1[348,440,257,45,46,47,48,49,50,51]",
                                formOID = "W58E4210A",
                                formActions = new FormActionsCollection
                                     (
                                    formaction.ToArray()
                                #region Old Code
                                     //   new FSREvent[]
                                     //   {
                                     //new FSREvent() { controlID="1.0", command="SelectRow" ,
                                     //                 gridAction =new GridAction(){gridID="1",gridRowUpdateEvents=gridrows}
                                     //               },
                                     //new FSREvent() { controlID="4", command="DoAction"  }
                                     //   }
                                #endregion
                                     )
                                 ,
                                stopOnWarning = "false"
                            };
                            asrequest = new ApplicationStackRequest()
                            {
                                outputType = "VERSION2",
                                allowCache = true,
                                action = "execute",
                                actionRequest = actionRequest,
                                stackId = response.stackId,//上一次返回的值
                                stateId = response.stateId,
                                rid = response.rid
                            };

                            response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                            needclose = true;
                            stackId = response.stackId;
                            stateId = response.stateId;
                            rid = response.rid;
                            //Console.WriteLine(response.JsonString);
                            Console.WriteLine($"{DateTime.Now.ToString()} NW单{NWOrderno}修改完成:{response.currentApp}");
                            if (response.currentApp.Contains("P58E4210_W58E4210A"))
                            {// 修改不成功，会停留在当前页面
                                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P58E4210_W58E4210A"))
                                {
                                    //不用做点什么
                                }
                            }
                            else
                            {
                                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P58E4210_W58E4210E"))
                                {
                                    obj = response.ToJObject();
                                    //应该查询到数据
                                    //string NAno = obj["fs_P58E4210_W58E4210E"]["data"]["gridData"]["rowset"]["0"]["z_DOCO_45"].ToString();
                                    execresult.Result = NWOrderno;
                                    //execresult.Message = response.JsonString;
                                }
                            }



                        }

                    }
                    else
                    {
                        throw new MQException("404", $"找不到单据{param.ordernumber},请联系管理员！");
                    }
                }
                #endregion
            }
            catch (MQException x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", x.ExceptionCode).ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
            }
            finally
            {
                #region Close

                ActionRequest actionRequest = new ActionRequest()
                {
                    //returnControlIDs = "1[17,18,19,20]",
                    formOID = "W58E4210A"
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    outputType = "VERSION2",
                    allowCache = true,
                    action = "close",
                    actionRequest = actionRequest,
                    stackId = stackId,//上一次返回的值
                    stateId = stateId,
                    rid = rid
                };
                if (!string.IsNullOrWhiteSpace(token) && needclose)
                {
                    AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                    //Console.WriteLine(response.JsonString);
                }
                #endregion
            }
            return execresult;
        }



        [HttpPost]
        public ActionResult<MQResponse> UpdateNWNOinvregion(dynamic objpram)
        {
            Log4Net.Debug(objpram);
            P4210param param = Common.JsonHelper.JsonToObject<P4210param>((objpram).ToString());
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            int stackId = 0;
            int stateId = 0;
            string rid = "";
            string token = "";
            bool needclose = false;
            try
            {
                if (string.IsNullOrWhiteSpace(param.username) || string.IsNullOrWhiteSpace(param.password))
                {
                    throw new Exception("请求的用户名或密码为空！");
                }

                token = SomeHandler.GetToken(param.username, param.password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }

                Console.WriteLine($"username:{param.username} Token:{token}");


                var data = new BLL.orderHandler().GetNWOrder(param.orderid);
                if (data[0].Rows.Count <= 0)
                {
                    throw new Exception($"找不到NW单{param.ordernumber}对应的拣货单");
                }

                string NWOrderno = data[0].Rows[0]["JdeOrderno"].ToString().Replace("NW", "");


                Console.WriteLine($"{DateTime.Now.ToString()} 查找NW单据 {NWOrderno}");

                #region 处理代码
                FormRequest formRequest = new FormRequest()
                {
                    //returnControlIDs = "1[45,46]",
                    formName = "P4210_W4210E",
                    version = "MBR001WD",
                    formServiceAction = "R",
                    bypassFormServiceEREvent = true
                   ,
                    formActions = new FormActionsCollection
                                 (
                                     new FSREvent[]
                                     {
                                      new FSREvent() { controlID="1[45]", command="SetQBEValue" ,value=NWOrderno },
                                      new FSREvent() { controlID="28", command="DoAction"  }
                                     }
                                 )
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    action = "open",
                    outputType = "VERSION2",
                    formName = "P4210_W4210E",
                    stackId = stackId,
                    stateId = stateId,
                    formRequest = formRequest

                };

                AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                //Console.WriteLine(response.JsonString);
                stackId = response.stackId;
                stateId = response.stateId;
                rid = response.rid;

                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4210_W4210E"))
                {
                    JObject obj = response.ToJObject();
                    int rowcount = Convert.ToInt16(obj["fs_P4210_W4210E"]["data"]["gridData"]["summary"]["records"]);
                    Console.WriteLine($"查询到{rowcount - 1}条记录");


                    if (rowcount > 1)
                    {
                        Console.WriteLine("选择第一条记录，并打开编辑界面");
                        ActionRequest actionRequest = new ActionRequest()
                        {
                            //returnControlIDs = "1[53,89,35,132,133,34,664]",
                            formOID = "W4210E",
                            formActions = new FormActionsCollection
                                  (
                                      new FSREvent[]
                                      {
                                      new FSREvent() { controlID="1.0", command="SelectRow"   },
                                      new FSREvent() { controlID="4", command="DoAction"  }
                                      }
                                  )
                             ,
                            stopOnWarning = "false"
                        };

                        asrequest = new ApplicationStackRequest()
                        {
                            outputType = "VERSION2",
                            allowCache = true,
                            action = "execute",
                            actionRequest = actionRequest,
                            stackId = stackId,
                            stateId = stateId,
                            rid = response.rid
                        };
                        response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                        stackId = response.stackId;
                        stateId = response.stateId;
                        rid = response.rid;
                        if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4210_W4210A"))
                        {
                            ///获取结果的总行数
                            obj = response.ToJObject();
                            rowcount = Convert.ToInt32(obj["fs_P4210_W4210A"]["data"]["gridData"]["summary"]["records"]);
                            List<gridrowupdateevents> gridrows = new List<gridrowupdateevents>();
                            List<gridcolumnevent> gridcols = new List<gridcolumnevent>();
                            List<int> delerows = new List<int>();




                            for (int i = 0; i < rowcount; i++)
                            {
                                Console.WriteLine($"正在处理第{i}行  原货位{obj["fs_P4210_W4210A"]["data"]["gridData"]["rowset"][i]["z_UITM_89"]["value"].ToString()}");
                                stackId = response.stackId;
                                stateId = response.stateId;
                                int rowindex = Convert.ToInt32(obj["fs_P4210_W4210A"]["data"]["gridData"]["rowset"][i]["rowIndex"]);
                                //正常NW单，需要ME码+批号+货位  来区分

                                JObject details = (JObject)obj["fs_P4210_W4210A"]["data"]["gridData"]["rowset"][i];//["z_LOCN_132"]["value"].ToString()

                                string primaykey = $"itemnumber='{details["z_UITM_89"]["value"]}' " +
                                                    $"and lotn='{details["z_LOTN_133"]["value"]}' " +
                                                    $"and location='{details["z_LOCN_132"]["value"].ToString().Replace("-", " ").Trim()}' ";
                                Console.WriteLine(primaykey);
                                DataRow[] dr = data[0].Select(primaykey);
                                decimal NewQty = 0;
                                if (dr.Length > 0)
                                {
                                    NewQty = Convert.ToDecimal(dr[0]["quantity"].ToString());
                                    gridcols = new List<gridcolumnevent>();
                                    gridcols.Add(new gridcolumnevent()
                                    {
                                        columnID = "53",
                                        command = "SetGridCellValue",
                                        value = NewQty.ToString()
                                    }
                                    );
                                    gridrows.Add(new gridrowupdateevents()
                                    {
                                        gridColumnEvents = gridcols,
                                        rowNumber = rowindex
                                    });
                                }
                                else
                                {
                                    delerows.Add(rowindex);
                                }

                            }
                            List<FSREvent> formaction = new List<FSREvent>();

                            delerows.ForEach(o => {
                                formaction.Add(new FSREvent()
                                {
                                    controlID = $"1.{o}",
                                    command = "SelectRow"
                                });
                            });
                            //如果存在删除行，则删除
                            if (formaction.Count > 0)
                                formaction.Add(new FSREvent() { controlID = "412", command = "DoAction" });
                            formaction.Add(new FSREvent()
                            {
                                controlID = "1.0",
                                command = "SelectRow",
                                gridAction = new GridAction() { gridID = "1", gridRowUpdateEvents = gridrows }
                            });
                            formaction.Add(new FSREvent() { controlID = "4", command = "DoAction" });



                            actionRequest = new ActionRequest()
                            {
                                returnControlIDs = "1[348,440,257,45,46,47,48,49,50,51]",
                                formOID = "W4210A",
                                formActions = new FormActionsCollection
                                     (  formaction.ToArray()   )
                                 ,
                                stopOnWarning = "false"
                            };
                            asrequest = new ApplicationStackRequest()
                            {
                                outputType = "VERSION2",
                                allowCache = true,
                                action = "execute",
                                actionRequest = actionRequest,
                                stackId = response.stackId,//上一次返回的值
                                stateId = response.stateId,
                                rid = response.rid
                            };

                            response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                            needclose = true;
                            stackId = response.stackId;
                            stateId = response.stateId;
                            rid = response.rid;
                            //Console.WriteLine(response.JsonString);
                            Console.WriteLine($"{DateTime.Now.ToString()} NW单{NWOrderno} 不带份额修改完成:{response.currentApp}");
                            if (response.currentApp.Contains("P4210_W4210A"))
                            {// 修改不成功，会停留在当前页面
                                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4210_W4210A"))
                                {
                                    //不用做点什么
                                }
                            }
                            else
                            {
                                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4210_W4210E"))
                                {
                                    obj = response.ToJObject();
                                    //应该查询到数据
                                    //string NAno = obj["fs_P58E4210_W58E4210E"]["data"]["gridData"]["rowset"]["0"]["z_DOCO_45"].ToString();
                                    execresult.Result = NWOrderno;
                                    execresult.Message = "";// response.JsonString;
                                }
                            }



                        }

                    }
                    else
                    {
                        throw new MQException("404", $"找不到单据{param.ordernumber},请联系管理员！");
                    }
                }
                #endregion
            }
            catch (MQException x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", x.ExceptionCode).ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
            }
            finally
            {
                #region Close

                ActionRequest actionRequest = new ActionRequest()
                {
                    //returnControlIDs = "1[17,18,19,20]",
                    formOID = "W4210A"
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    outputType = "VERSION2",
                    allowCache = true,
                    action = "close",
                    actionRequest = actionRequest,
                    stackId = stackId,//上一次返回的值
                    stateId = stateId,
                    rid = rid
                };
                if (!string.IsNullOrWhiteSpace(token) && needclose)
                {
                    AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                    //Console.WriteLine(response.JsonString);
                }
                #endregion
            }
            return execresult;
        }
    }
}